from aip import AipFace
import base64
import os
from pypinyin import lazy_pinyin, Style

class BaDuFace:
    
    def __init__(self,AppID='119459065',APIKey='ki2y6eS0zh6AQUQfaNe4wQIz',SecretKey='JHpV7hiLbyxamlv2FaZ1O6RZNJIYmLoQ'):
        self.APP_ID = AppID
        self.API_KEY = APIKey
        self.SECRET_KEY = SecretKey

        self.client = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY)

    # 注册人脸
    def name_to_pinyin(self,text):
        style = Style.TONE3
        name_list=lazy_pinyin(text, style=style)
        return ''.join(name_list)
    
    def add_user(self,file_obj,userId):
        image = base64.b64encode(file_obj.read()).decode('utf-8')

        imageType = "BASE64"

        groupId = "dome_1"

        userId=self.name_to_pinyin('迪丽热巴')
        """ 调用人脸注册 """
        res = self.client.addUser(image, imageType, groupId, userId);

        return  res
        # """ 如果有可选参数 """
        # options = {}
        # options["user_info"] = "彭于晏"
        # options["quality_control"] = "NORMAL"
        # options["liveness_control"] = "LOW"
        # options["action_type"] = "REPLACE"

        # """ 带参数调用人脸注册 """
        # self.client.addUser(image, imageType, groupId, userId, options)

    def delete(self,faceToken,userId):
        groupId = "dome_1"
        """ 调用人脸删除 """
        res = self.client.faceDelete(userId, groupId, faceToken)
        return res
    
    def search(self,file_obj):
        image = base64.b64encode(file_obj.read()).decode('utf-8')
        imageType = "BASE64"
        groupIdList = "dome_1"
        """ 调用人脸搜索 """
        # res = self.client.search(image, imageType, groupIdList)
        """ 如果有可选参数 """
        options = {}
        options["match_threshold"] = 70
        # options["quality_control"] = "NORMAL"
        # options["liveness_control"] = "LOW"
        # # options["user_id"] = "233451"
        # options["max_user_num"] = 3

        """ 带参数调用人脸搜索 """
        res=self.client.search(image, imageType, groupIdList, options)
        return res


